package luit.mmt02.xuly;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;

import luit.mmt02.doituong.OneMail;

import org.apache.commons.codec.net.QuotedPrintableCodec;

import android.util.Base64;
import android.util.Log;
public class ConvertMessageToList 
{
	
	String tag = "convertLog";
	OneMail om;
	Boolean flag_plaintext = false;
	XuLyChuoi xlchuoi;
	
	
	public ConvertMessageToList() {
		super();
		xlchuoi = new XuLyChuoi();
		// TODO Auto-generated constructor stub
	}
	public boolean unread_to_read(Message[]mes, int i)
	{
		try {
			mes[i].setFlag(Flags.Flag.SEEN, true);
			Log.v(tag, "thu da read " + i) ;
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.v(tag, "loi unread to read" +e.toString());
			return false;
		}
	}
	public boolean delete_message(Message[]mes, int i)
	{
		try {
			mes[i].setFlag(Flags.Flag.DELETED, true);
			Log.v(tag, "delete thanh cong mail " + i) ;
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.v(tag, "loi set favorite" +e.toString());
			return false;
		}
		
	}
	public boolean set_favorite_true(Message[]mes, int i)
	{
		try {
			mes[i].setFlag(Flags.Flag.FLAGGED, true);
			Log.v(tag, "gan favorite is TRUE " + i) ;
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.v(tag, "loi set favorite" +e.toString());
			return false;
		}
		
		
	}
	public boolean set_favorite_false(Message[]mes, int i)
	{
		try {
			mes[i].setFlag(Flags.Flag.FLAGGED, false);
			Log.v(tag, "gan favorite is FALSE " + i) ;
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.v(tag, "loi set favorite" +e.toString());
			return false;
		}
		
		
	}
	public List<OneMail>convert2(Message[]mess)
	{
		List<OneMail>list = new ArrayList<OneMail>();
		int n = mess.length;
		try
		{
			for(int i = n-1; i > n-6; i--)
			{
				if (i >=0)
				{
					OneMail om1 = get1mail(mess, i);
					list.add(om1);
				}
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			Log.i(tag, "loi conver 2");
		}
		return list;
	}

//	public void savefile(String fileName, InputStream inputStream)
//			throws Exception {
//
//		try{
//			if(fileName==null){
//				fileName = File.createTempFile("xxx", ".out").getName();
//			}
//			File savedir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/downloaddir");
//			savedir.mkdirs();
//			File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/downloaddir",fileName);
//			for(int i=0;file.exists();i++){
//				savedir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/downloaddir/"+fileName+i);
//				savedir.mkdirs();
//				file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/downloaddir/"+fileName+i,fileName);
//			}
//			
//				BufferedOutputStream bufferOUT = new BufferedOutputStream(
//						new FileOutputStream(file));
//
//				BufferedInputStream bufferIN = new BufferedInputStream(inputStream);
//
//				int abyte;
//				while ((abyte = bufferIN.read()) != -1) {
//					bufferOUT.write(abyte);
//				}
//
//				bufferOUT.flush();
//				bufferOUT.close();
//				bufferIN.close();
//			} catch (Exception e) {
//				Log.i(tag, "ERROR GET ATTACHMET" + e);
//			}
//	}
	
	
	
	public OneMail get1mail(Message[] mess, int i) {
		om = new OneMail();
		boolean flag_unread = false;

		try {
			//stt cua mail
			Log.v(tag, "thu thu " + i + "co sub : " + mess[i].getSubject().toString() );
			om.setId(mess.length - i);
			List<String> toAddresses = new ArrayList<String>();
			Address[] recipients = mess[i].getRecipients(Message.RecipientType.TO);
			for (Address address : recipients) {
			    toAddresses.add(address.toString());
			}
			om.setRecipients(toAddresses);
			
			Message m = mess[i];
			Flags flag = m.getFlags();
    		Flags.Flag [] fl = flag.getSystemFlags();
    		for(int i1 = 0; i1 < fl.length ; i1 ++)
    		{
    			if(fl[i1] == Flags.Flag.FLAGGED)
    			{
    				Log.v(tag, "co gan sao");
    				om.setFlagAttach(true);
    			}
    			if(fl[i1] == Flags.Flag.SEEN)
    			{
    				Log.v(tag, "thu doc roi1" + i);
    				om.setFlagRead(true);
    				
    			}
    			else
    			{
    				Log.v(tag, "thu chua read" + i);
    				flag_unread = true;
    			}
    			if(fl[i1] == Flags.Flag.RECENT)
    			{
    				Log.v(tag, "thu recent");
    			}
    			if(fl[i1] == Flags.Flag.ANSWERED)
    			{
    				Log.v(tag, "thu answered");
    			}
    		}
//			om.setDateSend(mess[i].getSentDate().toString());
    		try
			{
				String datesend = mess[i].getSentDate().toLocaleString();
				if(datesend.length() > 0)
				{
					Log.v(tag, "get duoc ngay" + datesend);
					om.setDateSend(datesend);
				}
				else
				{
					Log.v(tag, "chua get dc ngay");
					om.setDateSend("00h:00phuy");
				}
				
			}catch(Exception e1)
			{
				Log.v(tag, "Loi Get date send" + e1.toString());
			}
			om.setSub(mess[i].getSubject());
			om.setFrom(mess[i].getFrom()[0].toString());

			//Boolean flag_attachment = false;

			Object content = mess[i].getContent();
			if (content instanceof Multipart) {
				//flag_attachment = true;
				handleMultipart((Multipart) content);
			} else {
				//flag_attachment = false;				
				handlepart(mess[i]);

			}
//			if(flag_unread)
//			{
//				mess[i].setFlag(Flags.Flag.SEEN, false);
//				Log.v(tag, "gan chua doc cho thu : " + i);
//			}
			
			//kiem tra co encrypt hay khong
//			String []arr_body = om.getBody().split(expr)
			if(om.getBody().split("AES@").length >= 2 || om.getBody().split("DES@").length >= 2 
					|| om.getBody().split("3DES@").length >= 2)
			{
				om.setFlagEncrypt(true);
			}
			Log.v(tag, "########################################################################");

		} catch (Exception e) {
			// TODO: handle exception
			Log.i(tag, "ERR get1mail " + e.toString());
		}
		return om;
	}

	public void handleMultipart(Multipart content) throws Exception {
		String[] attach_names =
				new String[content.getCount() -1];
		Boolean flag_attachment = false;//xác định có attach hay ko, mặc định là false;
		Part[] parts =  new Part[content.getCount() - 1];
		Part part;
		int j=0;
		for (int i = 0; i < content.getCount(); i++) {
			part = content.getBodyPart(i);
			if(part.getDisposition()==null){
				handlepart(part);
			}else if(part.getDisposition().equalsIgnoreCase(part.ATTACHMENT)){
				parts[j] = part;
				attach_names[j] = parts[j].getFileName();
				j++;
			}
		}
		if(j!=0){
			flag_attachment = true;//có attach;
			
			om.set_attach_parts(parts);
			om.setAttach_names(attach_names);
			XuLyChuoi xlchuoi = new XuLyChuoi();
			for(String s:attach_names)
			{
				Log.v(tag, "att name:" + s);
				if(xlchuoi.check_file_encrypt(s))
				{
					om.setFlagEncrypt(true);
				}
			}
		}
		om.setFlagAttach(flag_attachment);

//		Log.i("So Attach", Integer.toString(content.getCount() - 1));
//		Log.i("max j", Integer.toString(j-1));
		
	}

	public void handlepart(Part part) throws Exception {
		

		try {
			String disposition = part.getDisposition();
			String contenttype = part.getContentType();
			String messbody = "";
			
//			Log.i("CONTENTTTYPE.length=", Integer.toString(contenttype.length()));
//			Log.i("CONTENTTYPR.TOLOWERCASE=",contenttype.toLowerCase());
			if(disposition ==null){
				if(contenttype.length() >= 10 && contenttype.toLowerCase().substring(0, 10).equals("text/plain")){
									
					BufferedReader bf=new BufferedReader(new InputStreamReader(part.getInputStream()));
					String read;
					while((read = bf.readLine())!=null){
						messbody = messbody+read+"\n";
					}
					
//					Log.i(tag, "message body");
//					Log.i("BODY GMAIL IN TEXT/Plain", messbody);
					bf.close();
					om.setBody(messbody);
					if(xlchuoi.check_encrypt(messbody) || xlchuoi.check_sign(messbody))
					{
						om.setFlagEncrypt(true);
					}
					else
					{
						om.setFlagEncrypt(false);
					}
					//part.writeTo(System.out);	
				}else if(contenttype.length() >= 10 && contenttype.toLowerCase().substring(0, 21).equals("multipart/alternative")){
					Boolean flag_content_encode_base64 = false;
					Boolean flag_content_endcode_quotedPrintable = false;
					int i=0;
					String dongdau="";
					BufferedReader bf=new BufferedReader(new InputStreamReader(part.getInputStream()));
					String read;
					while((read = bf.readLine())!=null){
						if(i==0){
							dongdau = read;
						}else if(i==2){
							if (read.equalsIgnoreCase("Content-Transfer-Encoding: base64")) {
								flag_content_encode_base64 = true;
							}else if(read.equalsIgnoreCase("Content-Transfer-Encoding: quoted-printable")){
								flag_content_endcode_quotedPrintable = true;
							
							}
							
						}
						else if(i > 2){
							
							if(read.equals(dongdau)){
								break;
							}
							messbody = messbody+read+"\n";
							
						}
						
						i++;
					}
					if(flag_content_encode_base64){
						byte[] bytes = Base64.decode(messbody, Base64.DEFAULT);
						messbody = new String(bytes,"UTF-8");
//						Log.i("DECODE64", "OK");
					}
					if(flag_content_endcode_quotedPrintable){
					
						QuotedPrintableCodec qp = new QuotedPrintableCodec("UTF-8");
						messbody = qp.decode(messbody, "UTF-8");//add thu vien commons-codec-1.6.jar giai ma quoted-printable;
						
//						Log.i("DECODE QUOTED PRINT", messbody);
					}
					
					
					/*
					 * Noi dung Chuoi MESSAGE BODY khi chua cat
					 * 
					 * --bcaec5015d07a2c38b04b4976c55 
					 * Content-Type: text/plain; charset=UTF-8 
					 * Content-Transfer-Encoding: quoted-printable
					 * WEB MAIL FROM GMAIL WITH ATTACH 
					 * TH=C3=81I TH=E1=BB=8A THU TH=E1=BA=A2O 
					 * --bcaec5015d07a2c38b04b4976c55 
					 * Content-Type:text/html; charset=UTF-8 
					 * Content-Transfer-Encoding:quoted-printable 
					 * <div>WEB MAIL FROM GMAIL WITH ATTACH</div> 
					 * <div>TH=C3=81I TH=E1=BB=8A THU TH=E1=BA=A2O</div> 
					 * --bcaec5015d07a2c38b04b4976c55--
					 */
					
					/* --_105f9dd0-c006-4377-b940-37dfbe95ac68_
					 Content-Type: text/plain; charset="utf-8"
					 Content-Transfer-Encoding: base64
					 DQpXRUIgTUFJTCBGUk9NIEhPVCBNQUlMIFdJVEggQVRUQUNIDQp0aMOhaSB0aOG7iyB0aHUgd

					 --_105f9dd0-c006-4377-b940-37dfbe95ac68_
					 Content-Type: text/html; charset="utf-8"
					 Content-Transfer-Encoding: base64
					 PGh0bWw+DQo8aGVhZD4NCjxzdHlsZT48IS0tDQouaG1tZXNzYWdlIFANCnsNCm1hcmdpbjowc
					 DQpwYWRkaW5nOjBweA0KfQ0KYm9keS5obW1lc3NhZ2UNCnsNCmZvbnQtc2l6ZTogMTBwdDs
					 --_105f9dd0-c006-4377-b940-37dfbe95ac68_--
					 */
//					Log.i(tag, "message body");
//					Log.i("BODY GMAIL IN MULTIPART/ALTERNATIVE", messbody);
					bf.close();
					om.setBody(messbody);
					if(xlchuoi.check_encrypt(messbody) || xlchuoi.check_sign(messbody))
					{
						om.setFlagEncrypt(true);
					}
					else
					{
						om.setFlagEncrypt(false);
					}
				}
			}/*else if(disposition.equalsIgnoreCase(part.ATTACHMENT)){
				System.out.println("<<<<----------Attachment: "+part.getFileName()+" : "+contenttype);
				
					savefile(part.getFileName(),part.getInputStream());

				
			}else if(disposition.equalsIgnoreCase(part.INLINE)){
				System.out.println("<<<<<-----------Inline: "+part.getFileName()+" : "+contenttype);
				savefile(part.getFileName(),part.getInputStream());
			}else System.out.println("<<<<<-----------Other: "+disposition);*/
		} catch (Exception e) {
			Log.i(tag	, "Error handlepart " +e.toString());
		}
		

	}
	
	public void Download_by_name(Message[]mess, int position, int p_att)
	{
		try
		{
			OneMail omG = get1mail(mess, position);
			if(omG.isFlagAttach())
			{
			//
				Log.v(tag, omG.getSub());
				Part[] partsG = omG.get_attach_parts();
				Log.i("parts.lengh=", Integer.toString(partsG.length));
//				for (int j = 0; j < partsG.length; j++) {
//					String file_name = partsG[j].getFileName();
////					omG.attach_down(partsG, j);
//					Log.v(tag, "Down thanh cong" +  file_name );
//				}
				String file_name = partsG[p_att].getFileName();
				omG.attach_down(partsG, p_att);
				Log.v(tag, "Down thanh cong" +  file_name + "tai vi tri : " + p_att);
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Loi download");
		}
	}
	
	
	
	

}
